#include <stdio.h>
#include <pthread.h>
#include <unistd.h>


//全局互斥锁
pthread_mutex_t mutex;
//全局条件变量
pthread_cond_t cond;


void * threadFunc1(void *)
{
    printf("sub thread 1 is running\n");
    //子线程加锁
    pthread_mutex_lock(&mutex);
    printf("\nsub thread 1 lock success\n");

    sleep(3);
    //通知等待该条件变量的线程
    pthread_cond_signal(&cond);
    printf("\nsub thread signal\n");
    //当执行到这里时，子线程没有解锁


    return NULL;
}


int main()
{
    //互斥锁的初始化
    pthread_mutex_init(&mutex, NULL);
    //条件变量的初始化
    pthread_cond_init(&cond, NULL);

    pthread_t pthid;
    pthread_create(&pthid, NULL, threadFunc1, NULL);

    //主线程加锁
    //pthread_mutex_lock(&mutex);
    //printf("main thread lock success\n");

    printf("\nmain thread wait cond\n");
    //主线程进入条件变量的等待状态
    //调用wait函数时，会有解锁的操作
    //
    //当wait函数返回时，会有加锁的操作
    //如果加锁没有成功，会继续阻塞
    pthread_cond_wait(&cond, &mutex);
    printf("\nmain thread after wait\n");

    //主线程解锁
    //pthread_mutex_unlock(&mutex);

    pthread_join(pthid, NULL);


    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    printf("main thread is exiting\n");
    return 0;
}

